package com.roncoo.pay.permission.service.impl;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.roncoo.pay.permission.entity.PmsRole;
import com.roncoo.pay.permission.entity.PmsUser;
import com.roncoo.pay.permission.entity.PmsUserRole;
import com.roncoo.pay.permission.repository.PmsRoleRepository;
import com.roncoo.pay.permission.repository.PmsUserRepository;
import com.roncoo.pay.permission.repository.PmsUserRoleRepository;
import com.roncoo.pay.permission.service.PmsUserRoleService;

/**
 * 操作员角色service接口实现
 *
 */
@Service("pmsUserRoleService")
public class PmsUserRoleServiceImpl implements PmsUserRoleService {
	@Autowired
	private PmsUserRoleRepository pmsUserRoleRepository;

	@Autowired
	private PmsUserRepository pmsUserRepository;

	@Autowired
	private PmsRoleRepository pmsRoleRepository;

	/**
	 * 根据操作员ID获得该操作员的所有角色id所拼成的String，每个ID用“,”分隔
	 * 
	 * @param operatorId
	 *            操作员ID
	 * @return roleIds
	 */
	public String getRoleIdsByOperatorId(String userId) {
		// 得到操作员和角色列表
		List<PmsUserRole> rpList = pmsUserRoleRepository.findByUserId(userId);
		// 构建StringBuffer来拼字符串
		StringBuilder roleIdsBuf = new StringBuilder("");
		for (PmsUserRole rp : rpList) {
			roleIdsBuf.append(rp.getRoleId()).append(",");
		}
		String roleIds = roleIdsBuf.toString();
		// 截取字符串
		if (StringUtils.isNotBlank(roleIds) && roleIds.length() > 0) {
			roleIds = roleIds.substring(0, roleIds.length() - 1);
		}
		return roleIds;
	}

	/**
	 * 根据操作员id，获取该操作员所有角色的编码集合
	 * 
	 * @param operatorId
	 * @return
	 */
	public Set<String> getRoleCodeByOperatorId(String userId) {
		// 得到操作员和角色列表
		List<PmsUserRole> rpList = pmsUserRoleRepository.findByUserId(userId);
		Set<String> roleCodeSet = new HashSet<String>();

		for (PmsUserRole rp : rpList) {
			String roleId = rp.getRoleId();
			PmsRole role = pmsRoleRepository.findOne(roleId);
			if (role == null) {
				continue;
			}
			roleCodeSet.add(role.getRoleCode());
		}

		return roleCodeSet;
	}

	/**
	 * 根据角色ID统计有多少个操作员关联到此角色.
	 * 
	 * @param roleId
	 *            .
	 * @return count.
	 */
	public int countOperatorByRoleId(String roleId) {
		List<PmsUserRole> operatorList = pmsUserRoleRepository.findByRoleId(roleId);
		if (operatorList == null || operatorList.isEmpty()) {
			return 0;
		} else {
			return operatorList.size();
		}
	}

	/**
	 * 根据操作员ID获得所有操作员－角色关联列表
	 */
	public List<PmsUserRole> listOperatorRoleByOperatorId(String userId) {
		return pmsUserRoleRepository.findByUserId(userId);
	}

	/**
	 * 保存操作員信息及其关联的角色.
	 * 
	 * @param pmsOperator
	 *            .
	 * @param OperatorRoleStr
	 *            .
	 */
	public void saveOperator(PmsUser pmsOperator, String OperatorRoleStr) {
		// 保存操作员信息
		pmsUserRepository.save(pmsOperator);
		// 保存角色关联信息
		if (StringUtils.isNotBlank(OperatorRoleStr) && OperatorRoleStr.length() > 0) {
			saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
		}
	}

	/**
	 * 根据角色ID查询用户
	 * 
	 * @param roleId
	 * @return
	 */
	public List<PmsUser> listOperatorByRoleId(String roleId) {
		List<PmsUserRole> list = pmsUserRoleRepository.findByRoleId(roleId);
		List<PmsUser> userList = Lists.newArrayList();
		for(PmsUserRole userRole : list){
			userList.add(pmsUserRepository.findOne(userRole.getUserId()));
		}
		return userList;
	}

	/**
	 * 修改操作員信息及其关联的角色.
	 * 
	 * @param pmsOperator
	 *            .
	 * @param OperatorRoleStr
	 *            .
	 */
	public void updateOperator(PmsUser pmsOperator, String OperatorRoleStr) {
		pmsUserRepository.save(pmsOperator);
		// 更新角色信息
		saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
	}

	/**
	 * 保存用户和角色之间的关联关系
	 */
	private void saveOrUpdateOperatorRole(String operatorId, String roleIdsStr) {
		// 删除原来的角色与操作员关联
		List<PmsUserRole> listPmsOperatorRoles = pmsUserRoleRepository.findByUserId(operatorId);
		Map<String, PmsUserRole> delMap = Maps.newHashMap();
		for (PmsUserRole pmsOperatorRole : listPmsOperatorRoles) {
			delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
		}
		if (StringUtils.isNotBlank(roleIdsStr)) {
			// 创建新的关联
			String[] roleIds = roleIdsStr.split(",");
			for (int i = 0; i < roleIds.length; i++) {
				String roleId = roleIds[i];
				if (delMap.get(roleId) == null) {
					PmsUserRole pmsUserRole = new PmsUserRole();
					pmsUserRole.setUserId(operatorId);
					pmsUserRole.setRoleId(roleId);
					pmsUserRoleRepository.save(pmsUserRole);
				} else {
					delMap.remove(roleId);
				}
			}
		}

		Iterator<String> iterator = delMap.keySet().iterator();
		while (iterator.hasNext()) {
			String roleId = iterator.next();
			pmsUserRoleRepository.deleteByRoleIdAndUserId(roleId, operatorId);
		}
	}
}
